package com.controller.task;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.common.DateUtils;
import com.common.easyui.EasyuiUtils;
import com.common.PropertiesUtils;
import com.dao.sys.SysFileMapper;
import com.dao.task.AtDelayMapper;
import com.dao.task.AtInforMapper;
import com.dao.task.AtProjectMapper;
import com.dao.task.AtProjectresultMapper;
import com.dao.task.TaskMapper;
import com.model.sys.SysUser;
import com.model.task.AtDelay;
import com.model.task.AtProject;
import com.model.task.AtProjectresult;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Controller
public class TaskManageController {
	static final Logger logger = LoggerFactory.getLogger(TaskManageController.class);
	@Autowired
	private AtProjectMapper atProjectMapper;
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private AtProjectresultMapper atProjectresultMapper;
	@Autowired
	private AtInforMapper atInforMapper;
	@Autowired
	private AtDelayMapper atDelayMapper;
	@Autowired
	private SysFileMapper sysFileMapper;

	@RequestMapping("/task/taskmanage")
	public String taskTask(HttpServletRequest request) {
		int week = DateUtils.getWeek(new Date());
		String year = DateUtils.getCurrentYear();
		request.setAttribute("yaw", year + week);
		return "task/TaskManage";
	}

	@RequestMapping("/task/taskList")
	public String taskList(HttpServletRequest request) {
		String proId = request.getParameter("proId");

		HashMap<String, Object> hashtable = new HashMap<>();
		hashtable.put("proId", proId);
//		hashtable.put("createtime", currentdate);
		List<HashMap<String, Object>> list = taskMapper.selectTaskList(hashtable);

		request.setAttribute("contentlist", list);
		request.setAttribute("proId", proId);
		return "task/TaskList";
	}

	@RequestMapping("/task/exportExcel")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.reset();
		request.setCharacterEncoding("utf-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/x-msdownload");

		String proId = request.getParameter("proId");

		HashMap<String, Object> hashtable = new HashMap<>();
		hashtable.put("proId", proId);
//		hashtable.put("createtime", currentdate);
		List<HashMap<String, Object>> list = taskMapper.selectTaskList(hashtable);
		String filename = "督办事项列表";
		if (list.size() > 0) {
			filename = (String) list.get(0).get("PRO_CONTENT");
		}
		filename = URLEncoder.encode(filename + ".xls", "UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

		String templateName = "taskList.ftl";
		Template template = com.common.template.FreeMarkerTemplateUtils.getTemplate(templateName);
		Writer writer = response.getWriter();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			dataMap.put("listData", list);
			template.process(dataMap, writer);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.flush();
		writer.close();
	}

	/*
	 * 采用spring提供的上传文件的方法
	 */
	@RequestMapping(value = "/task/upload", produces = "text/plain;charset=UTF-8")
	public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
		String basepath = PropertiesUtils.getValue("filepath");
		long startTime = System.currentTimeMillis();
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		String proId = request.getParameter("proId");
		int week = DateUtils.getWeek(new Date());
		String year = DateUtils.getCurrentYear();
		String baseFilename = proId + "-" + year + week + "-";
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					File dir = new File(basepath);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					String path = basepath + "/" + baseFilename + file.getOriginalFilename();
					// 上传
					file.transferTo(new File(path));
				}

			}

		}
		long endTime = System.currentTimeMillis();
		return "";
	}

	@RequestMapping(value = "/task/selectTasks", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectTasks(HttpServletRequest request) {
		try {
			HashMap<String, Object> hashtable = new HashMap<>();
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			String jsonString = "";
			if (request.getParameter("page") != null) {
				int page = 0;
				int size = 10;
				page = Integer.parseInt(request.getParameter("page"));
				page = (page - 1) * size;
				size = Integer.parseInt(request.getParameter("rows"));
				hashtable.put("PAGENUM", page);
				hashtable.put("PAGESIZE", size);
			}
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			String state = request.getParameter("state");
			if (state.equals("1")) {
				hashtable.put("userid", sysUser.getUserid());
				hashtable.put("username", sysUser.getUsername());
				String infname = request.getParameter("queryname");
				if (infname != null && !infname.equals("")) {
					hashtable.put("inf_name", infname);
				}
				list = taskMapper.selectTasks(hashtable);
				jsonString = JSON.toJSONString(list);
				jsonString = EasyuiUtils.getDatagridPageJson(jsonString, taskMapper.selectStatistaskCount(hashtable));
			} else if (state.equals("0")) {
				int week = DateUtils.getWeek(new Date());
				String year = DateUtils.getCurrentYear();
				hashtable.put("week", year + week);
				hashtable.put("userid", sysUser.getUserid());
				hashtable.put("username", sysUser.getUsername());
				list = taskMapper.selectMytask(hashtable);
				jsonString = JSON.toJSONString(list);
				jsonString = EasyuiUtils.getDatagridPageJson(jsonString, taskMapper.selectMytaskCount(hashtable));
			}
			logger.info("selectTasks:{}", jsonString);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("selectMytask:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/task/selectTasksDelay", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectTasksDelay(HttpServletRequest request) {
		try {
			HashMap<String, Object> hashtable = new HashMap<>();
			String jsonString = "";
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			String proId = request.getParameter("proId");
			hashtable.put("proId", proId);
			list = taskMapper.selectDelayList(hashtable);
			jsonString = JSON.toJSONString(list);
			logger.info("selectTasksDelay:{}", jsonString);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("selectTasksDelay:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/task/saveProjectresult", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String saveProjectresult(HttpServletRequest request) {
		try {
			String resultString = "保存成功!";
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			int week = DateUtils.getWeek(new Date());
			String year = DateUtils.getCurrentYear();
			String infId = request.getParameter("inf_id");
			String proId = request.getParameter("proId");
			AtProjectresult model = atProjectresultMapper.selectByPrimaryKey(Integer.parseInt(year + week),
					sysUser.getUserid(), infId, proId);
			int progress = 0;
			if (request.getParameter("progress") != null) {
				progress = Integer.parseInt(request.getParameter("progress"));
			}
			if (model == null) {
				model = new AtProjectresult();
				model.setInfId(infId);
				model.setProrWeek(Integer.parseInt(year + week));
				model.setProrCreattime(df.format(new Date()));
				model.setProExecuteuserid(sysUser.getUserid());
				model.setProrContent(request.getParameter("content"));
				model.setProrProgress(progress);
				model.setProId(proId);
				resultString = atProjectresultMapper.insert(model) > 0 ? "保存成功!" : "保存失败!";
			} else {
				model.setProrProgress(progress);
				model.setProrContent(request.getParameter("content"));
				resultString = atProjectresultMapper.updateByPrimaryKey(model) > 0 ? "保存成功!" : "保存失败!";
			}
			// 保存计划完成时间
			AtProject atProject = atProjectMapper.selectByPrimaryKey(infId, sysUser.getUserid(), proId);
			atProject.setProPlanfinishdate(request.getParameter("planDate"));

			atProjectMapper.updateByPrimaryKey(atProject);
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/task/saveProjectresultDelay", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String saveProjectresultDelay(HttpServletRequest request) {
		try {
			String resultString = "保存成功!";
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			String infId = request.getParameter("inf_id");
			String proId = request.getParameter("proId");
			String planDateNew = request.getParameter("planDateNew");
			String planDateOld = request.getParameter("planDateOld");
			String content = request.getParameter("content");
			AtDelay model = new AtDelay();
			model.setLevId(UUID.randomUUID().toString());
			model.setProId(proId);
			model.setLevNewdate(planDateNew);
			model.setLevOlddate(planDateOld);
			model.setLevTime(DateUtils.getCurrentTime());
			model.setLevReson(content);
			resultString = atDelayMapper.insert(model) > 0 ? "保存成功!" : "保存失败!";

			// 保存计划完成时间
			AtProject atProject = atProjectMapper.selectByPrimaryKey(infId, sysUser.getUserid(), proId);
			atProject.setProPlanfinishdate(planDateNew);
			atProjectMapper.updateByPrimaryKey(atProject);
//			
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/task/selectResultCommitNum", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectResultCommitNum(HttpServletRequest request) {
		try {
			HashMap<String, Object> hashtable = new HashMap<>();
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			hashtable.put("infid", request.getParameter("inf_id"));
			hashtable.put("userid", sysUser.getUserid());
			hashtable.put("proId", request.getParameter("proId"));
			int num = taskMapper.selectResultCommitNum(hashtable);
			String jsonString = num + "";
			logger.info("selectResultCommitNum:{}", jsonString);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("selectResultCommitNum:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/task/commitProjectresult", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String commitProjectresult(HttpServletRequest request) {
		try {
			String resultString = "提交成功!";
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			int week = DateUtils.getWeek(new Date());
			String year = DateUtils.getCurrentYear();
			String infId = request.getParameter("inf_id");
			String proId = request.getParameter("proId");
			AtProjectresult model = atProjectresultMapper.selectByPrimaryKey(Integer.parseInt(year + week),
					sysUser.getUserid(), infId, proId);
			if (model == null) {
				model = new AtProjectresult();
				model.setInfId(infId);
				model.setProrWeek(Integer.parseInt(year + week));
				model.setProrCreattime(df.format(new Date()));
				model.setProExecuteuserid(sysUser.getUserid());
				model.setProrContent(request.getParameter("content"));
				model.setProId(proId);
				resultString = atProjectresultMapper.insert(model) > 0 ? "保存成功!" : "保存失败!";
			} else {
			}
			model.setProrCommittime(df.format(new Date()));
			model.setProrContent(request.getParameter("content"));
			int progress = 0;
			if (request.getParameter("progress") != null) {
				progress = Integer.parseInt(request.getParameter("progress"));
			}
			model.setProrProgress(progress);
			resultString = atProjectresultMapper.updateByPrimaryKey(model) > 0 ? "提交成功!" : "提交失败!";
			// 保存计划完成时间
			AtProject atProject = atProjectMapper.selectByPrimaryKey(infId, sysUser.getUserid(), proId);
			atProject.setProPlanfinishdate(request.getParameter("planDate"));
			atProject.setProCoee(progress + "");
			if (progress == 100) {
				atProject.setProOverdue(1);// 提交后设置状态为完成
				atProject.setProValidatetime(DateUtils.getCurrentTime());// 任务完成时间
			}
			atProjectMapper.updateByPrimaryKey(atProject);
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}
}
